const models = require(__base + '/models');
const errcode = require(__util + "/errcode")
const { isJSON } = require(__util + "/help");
const ct = require(__util + "/catch"); // 路由错误捕获(不使用则不会捕获异常错误)

module.exports = ct(async (req, res) => {
  const {
    id, appIcon, appName, appType, appUrl, platform = '', seqNum, gteVersion, lteVersion, appCode, chatDapp = false, uiOptions
  } = req.body
  
  if (!appIcon || !appName || !appType || !appUrl) {
    return res.json(errcode.APP_UNFULL)
  }

  if (uiOptions && !isJSON(uiOptions)) {
    return res.json(errcode.APP_UIOPTIONS_INVALID)
  }

  // 更新数据
  const updateData = {
    appName: appName,
    appType: appType,
    appUrl: appUrl,
    platform: platform,
    seqNum: seqNum,
    gteVersion: gteVersion,
    lteVersion: lteVersion,
    appCode: appCode,
    chatDapp: chatDapp
  }
  if (uiOptions) {
    updateData.uiOptions = JSON.parse(uiOptions)
  }
  // 不存储带有域名地址的链接, 防止写死的地址不易于扩展
  if (!appIcon.startsWith('http://') && !appIcon.startsWith('https://')) {
    updateData.appIcon = appIcon
  }

  await models.ThirdPartyApp.update(updateData, {
    where: {
      id: id
    }
  })

  return res.json(
    errcode.SUCCESS()
  )
})